#include "../MainWindow.h"
#include "ui_MainWindow.h"

#include <QSplitter>
#include "windows/AddRepositoryDialog.h"
#include "../../common/services/ServiceLocator.h"
#include "presenters/MainWindowPresenter.h"
#include "models/Repository.h"

// Constructor and destructor.

MainWindow::MainWindow(
	ServiceLocator *servicesLocator, QWidget *parent, Qt::WindowFlags flags)
	: QMainWindow(parent, flags)
{
	createUi();
	createTrayIcon();

	presenter = new MainWindowPresenter(this);
	ui->repositoriesListWidget->setServiceLocator(servicesLocator);
}

MainWindow::~MainWindow()
{
	delete presenter;
	delete trayIcon;
	delete ui;
}

// Methods.

void MainWindow::init()
{
	ui->repositoriesListWidget->loadRepositoriesList();
}

// IMainWindowView implementation.

Repository *MainWindow::showAddRepositoryDialog()
{
	AddRepositoryDialog addRepositoryDialog(this);
	bool accepted = (addRepositoryDialog.exec() == QDialog::Accepted);
	if (accepted)
	{
		QString name = addRepositoryDialog.getRepositoryName();
		Repository *repository = new Repository(name);

		return repository;
	}

	return NULL;
}

void MainWindow::toggleVisibility()
{
	if (isVisible())
	{
		hide();
	}
	else
	{
		show();
	}
}

void MainWindow::hideWindow()
{
	hide();
}

void MainWindow::closeWindow()
{
	close();
}

// QWidget overrides.

void MainWindow::closeEvent(QCloseEvent *event)
{
	bool ignore = presenter->onClose();
	if (ignore)
	{
		event->ignore();
	}
	else
	{
		event->accept();
	}
}

// Slots.

void MainWindow::on_addRepositoryAction_triggered()
{
	presenter->onAddRepository();
}

void MainWindow::on_removeRepositoryAction_triggered()
{
	//
}

void MainWindow::on_editRepositoryAction_triggered()
{
	//
}

void MainWindow::on_preferencesAction_triggered()
{
	//
}

void MainWindow::on_exitAction_triggered()
{
	presenter->onExit();
}

void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
	if (reason == QSystemTrayIcon::Trigger)
	{
		presenter->onTrayIconClicked();
	}
}

// Helpers.

void MainWindow::createUi()
{
	ui = new Ui::MainWindow();
	ui->setupUi(this);
}

void MainWindow::createTrayIcon()
{
	trayIcon = new QSystemTrayIcon(QIcon(":/images/eyes.png"), this);
	trayIcon->show();
	connect(
			trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
			this, SLOT(onTrayIconActivated(QSystemTrayIcon::ActivationReason)));
}
